package com.sofwin.interceptor;

import com.sofwin.Constants;
import com.sofwin.pojo.SysUser;
import com.sofwin.service.UserService;
import com.sofwin.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
@Component()
public class MonitorInterceptor implements HandlerInterceptor {
    private long beginDate;

    @Autowired
    private UserService userService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 时间1
        beginDate = System.currentTimeMillis();
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 时间2
        long endDate = System.currentTimeMillis();
        long request_date = endDate-beginDate;
        HttpSession session = request.getSession();
        SysUser user =(SysUser) session.getAttribute(Constants.CURR_USER);
        String ip = request.getRemoteAddr();
        String url = request.getRequestURI();
        String currDate = DateUtil.getDateStr(new Date(),"yyyy-MM-dd HH:mm:ss");
        // 插入monitor数据
        // 当前访问的用户
        // 封装sysMonitor，将它插入到数据库
        userService.saveMonitor(user.getId(),currDate,url,request_date,ip);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
